package server.fsm;

import etc.SynchronizationParameters;
import etc.Utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import javax.swing.JOptionPane;

public class AuthorizedState extends GenericServerState {

	@Override
	public String logout() {
		getServerContext().setCurrentServerState( new WaitingState(), "Client logged out, waiting for re-authorization." );
		return "<logout result='OK'>You have logged out from the server.</logout>";
	}

	@Override
	public String listFiles() {
		File rootFolder = new File( SynchronizationParameters.getLocalPath() );
		
		if( rootFolder == null ) {
			JOptionPane.showMessageDialog(null, "It seems that the local synchronozation "
					+ "folder that, you selected is unreachable.\n"
					+ "Please consider changing local synchronization folder setting.",
					"I/O Error", JOptionPane.ERROR_MESSAGE );
			return "<error type='IO_ERROR'>Could not open synchronozation folder on server.</error>";
		}

		ArrayList<File> fileList = Utils.listFilesInDir( rootFolder );

		return Utils.fileListToXMLString(fileList, rootFolder);
	}

	@Override
	public String delete( String file ) {
		File delFile = new File(SynchronizationParameters.getLocalPath()  + "\\" + file.replace('/', '\\') );

		if( (delFile == null) || (!delFile.exists()) ){
			return "<delete result='FAILED' file='"+file+"'>Specified file does not exist.</delete>";
		}else{
			try{
				if( delFile.delete() ) {
					return "<delete result='OK' file='"+file+"' />";
				}else{
					return "<delete result='FAILED' file='"+file+"'>Unable to delete file.</delete>";
				}
			}catch(Exception e) {
				return "<delete result='FAILED' file='"+file+"'>Specified file does not exist.</delete>";
			}
		}
	}

	@Override
	public String uploadFile( String file, Long fileSizeBytes, int chunkSize ) {
		try{
			File sourceFile = new File( SynchronizationParameters.getLocalPath() + '\\' + file.replace('/', '\\') );
			if( sourceFile.exists()
					&& ( fileSizeBytes.compareTo( sourceFile.length() ) == 0 ) ) {
				
				getServerContext().setCurrentServerState( new UploadingState(file, fileSizeBytes, chunkSize), "Uploading file '"+file+"'." );
				return "<upload file='"+file+"' size='"+fileSizeBytes.toString()+"' lastModified='"+sourceFile.lastModified()+"' />";
			}
		}catch(Exception e) {}

		return "<error type='FILE_NOT_FOUND'>No matching file found on server to upload.</error>";
	}

	@Override
	public String downloadFile( String file, Long size, Long lastModified ) {
		try {
			getServerContext().setCurrentServerState( new DownloadingState(file, size, lastModified), "Downloading file '" + file + "'." );
			return "<waiting file='" + file + "' size='" + size.toString() + "' />";
		} catch (FileNotFoundException ex) {}

		return "<error type='IO_ERROR'>An IO error occured while trying to download the file.</error>";
	}

}
